// subpackage/pages/tuanOil/stationList.js
let _page, _this;
import requestUtil from '../../../baseRequest.js'
import requestUrl from '../../../requestUrl.js';
import { $Message } from '../../../components/base/index'
let h;
wx.getSystemInfo({
  success: function (res) {
    h = res.windowHeight - 30
  },
})
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //全部油站
    totalStationList:[],
    //显示油站
    showStationList:[],
    //可以选择的油站
    canSelectStation:[],
    //中间状态油站
    tempStationList:[],

    option1: [
      { text: '距离最近', value: 'distance' },
      { text: '价格最低', value: 'price' },
    ],
    option2: [
      { text: '92号油', value: '92' },
      { text: '95号油', value: '95' },
      { text: '0号油', value: '0' },
      { text: '98号油', value: '98' },
    ],
    value1: 'distance',
    value2: '92',
    bannerUrl:requestUrl.baseImagePrefixUrl+'/31eecaeb-cb2b-42e0-99d5-72451bedf9d8.png',
    page:1,
    scorllH:h-190,
    province :'北京市',
    city:'市辖区',
    district:'东城区',
  },

  getCurrentPlace(){
    _this = this;
    wx.getLocation({
      altitude: 'altitude',
      success:res=>{
        _this.getRealLocation(res.latitude, res.longitude);
      }
    })
  },
  getRealLocation(latitude, longitude) {
    // _page = this;
    // wx.request({
    //   url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=VEJBZ-M5YLX-KZN4O-7VWPS-VGOFT-46FXA`,
    //   header: {
    //     'Content-Type': 'application/json'
    //   },
    //   success: function (res) {
    //     //获取省市县
    //     const { city, province, district } = res.data.result.address_component;
    //     _page.setData({
    //       province,
    //       city,
    //       district,
    //     })
    //   }
    // })
  },
  reGetTotalStation(){
    requestUtil.getRequest(requestUrl.tuanOil.getStationList,{},(res=>{
      if(!res.hasError){
        wx.setStorageSync('totalStationList', res.result.list);
        wx.setStorageSync('queryStationDate', new Date());
        this.setData({
          totalStationList : res.result.list,
        })
        this.initCanSelectStation();
        this.initShowList();
        this.countDownPrice();
      }
    }))
  },
  getStationList(){
    const totalStationList = wx.getStorageSync('totalStationList');
    const queryDate = wx.getStorageSync('queryStationDate');
    if(queryDate){
      var queryTime = new Date(queryDate);
      var now = new Date();
      if(queryTime.getDate()===now.getDate()){
        if(totalStationList){
          this.setData({
            totalStationList : totalStationList,
          });
          this.initCanSelectStation();
          this.initShowList();
          this.countDownPrice();
        }else{
          this.reGetTotalStation();
        }
      }else{
        this.reGetTotalStation();
      }
    }else{
      this.reGetTotalStation();
    }
  },
  toNextPage(){
    let total = this.data.tempStationList.length;
    if(5* this.data.page>=total){
      this.showErrorMessage("已加载全部数据");
    }else{
      let begin = 5*this.data.page;
      let end = begin+5;
      let tempList = this.data.tempStationList.slice(begin,end);
      this.setData({
        showStationList :this.data.showStationList.concat(tempList),
        page:this.data.page+1,
      })
      this.countDownPrice();
    }
  },
  toStationInfo(event){
    let stationId  = event.currentTarget.dataset.stationid;
    this.data.showStationList.forEach(item=>{
      if(item.gasId === stationId){
        wx.setStorageSync('gasStation', item);
      }
    })
    wx.navigateTo({
      url: '/subpackage/pages/tuanOil/stationInfo?stationId='+stationId+'&oilType='+this.data.value2,
    })
  },
  countDownPrice(){
    let tempList =[];
    if(this.data.showStationList){
      this.data.showStationList.forEach(item=>{
        let priceList = item.oilPriceList;
        let tempPriceList =[];
        priceList.forEach(price=>{
          tempPriceList.push({...price,
            downPrice:(price.priceOfficial-price.priceYfq ).toFixed(2),
            downOilPrice:(price.priceGun-price.priceYfq ).toFixed(2)})
        })
        item.oilPriceList = tempPriceList;
        tempList.push(item);
      })
    }
    this.setData({
      showStationList:tempList,
    })
  },
  changeDistanceType(value){
    this.setData({
      value1:value.detail,
      page:1,
    })
    this.initShowList();
  },
  changeOilType(value){
    this.setData({
      value2:value.detail,
      page:1,
    })
    this.initShowList();
  },
  initShowList(){
    if(this.data.canSelectStation && this.data.canSelectStation.length>0){
      if(this.data.value1==='distance'){
        let tempList = [];
        this.data.canSelectStation.forEach(item=>{
          if(item.oilPriceList){
            item.oilPriceList.forEach(oil=>{
              if(oil.oilNo==this.data.value2){
                tempList.push(item);
              }
            })
          }
        })
        this.setData({
          tempStationList : tempList,
          showStationList: tempList.slice(0,5),
          page:1
        })
        this.countDownPrice();
      }else if(this.data.value1 === 'price'){
        let tempListxx = [];
        this.data.canSelectStation.forEach(item=>{
          if(item.oilPriceList){
            item.oilPriceList.forEach(oil=>{
              if(oil.oilNo==this.data.value2){
                tempListxx.push(item);
              }
            })
          }
        })
        let tempList = tempListxx.sort((a,b)=>{
          let aPrice = 0,bPrice =0;
          if(a.oilPriceList){
            a.oilPriceList.forEach(item=>{
              if(item.oilNo==this.data.value2){
                aPrice = item.priceYfq
              }
            })
          }
          if(b.oilPriceList){
            b.oilPriceList.forEach(item=>{
              if(item.oilNo==this.data.value2){
                bPrice = item.priceYfq
              }
            })
          }
          return aPrice - bPrice;
        })
        this.setData({
          tempStationList : tempList,
          showStationList: tempList.slice(0,5),
          page:1
        })
        this.countDownPrice();
      }
    }
  },
  initCanSelectStation(){
    let countyList = [], cityList=[], provinceList =[];
    if(this.data.totalStationList && this.data.totalStationList.length>0){
      if(this.data.province && this.data.city && this.data.district){
        this.data.totalStationList.forEach(s=>{
          let ifIn = false;
          if(s.provinceName==this.data.province){
            if(s.cityName == this.data.city){
              if(s.countyName == this.data.district){
                countyList.push(s);
                ifIn = true;
              }
              if(!ifIn){
                cityList.push(s);
                ifIn = true;
              }
            }
            if(!ifIn){
              provinceList.push(s);
            }
          }
          ifIn = false;
        })
        let canSelectStation = countyList.concat(cityList).concat(provinceList);
        this.setData({
          canSelectStation :canSelectStation,
        })
      }
    }
  },
  showErrorMessage(msg) {
    $Message({
      content: msg,
      type: 'error'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCurrentPlace();
    this.getStationList();
    this.initCanSelectStation();
    this.initShowList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})